package cn.sofwin.blog.service.impl;

import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.dao.UserDao;
import cn.sofwin.blog.service.UserService;
import cn.sofwin.blog.utils.DbUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

/**
 * 服务层
 *
 * @author LetCode
 * @since 1.0
 */
public class UserServiceImpl implements UserService {
    private SqlSession session=getSession();
    private UserDao userDao = getSession().getMapper(UserDao.class);

    /**
     * 私有的实例对象，用户实现单例模式
     */
    private static UserServiceImpl userService = new UserServiceImpl();

    /**
     * 将构造方法设为私有，用于实现单例模式
     */
    private UserServiceImpl() {
        super();
    }

    /**
     * 对外提供的静态方法，用于获取服务实例
     *
     * @return
     */
    public static UserService getInstance() {
        return userService;
    }

    @Override
    public SqlSession getSession() {
        return DbUtils.openSession();
    }

    @Override
    public User login(String username, String password) {
        User user = userDao.selectByUsername(username);
        if (user == null) {
            return null;
        }
        password = DigestUtils.md5Hex(password);
        //密码不匹配，将user置空，代表登录失败
        if (!user.getPassword().equals(password)) {
            return null;
        }

        return user;
    }

    @Override
    public User register(String username, String password, String nickname) {
        User user = userDao.selectByUsername(username);
        if (user != null) {
            return null;
        }
        user = new User();
        user.setNickname(nickname);
        user.setUsername(username);
        user.setPassword(DigestUtils.md5Hex(password));
        user.setGender(0);

        int id = userDao.insert(user);
        user.setId(id);
        return user;
    }

    @Override
    public void updateProfile(User user, String password, String nickname, String avatar) {
        if (StringUtils.isNoneBlank(password)){
            password=DigestUtils.md5Hex(password);
            user.setPassword(password);
        }
        user.setNickname(nickname);
        user.setAvatar(avatar);
        userDao.update(user);
    }

    //TODO
    @Override
    public User findByUsername(String username) {
        return userDao.selectByUsername(username);
    }
}